package org.example.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidDemo {

    Connection conn;

    public DruidDemo() {
        this.connect();
    }

    public void connect() {
        // 使用druid连接池
        // 1. 加载配置
        try {
            Properties prop = new Properties();
            // prop.load(DruidDemo.class.getClassLoader().getResourceAsStream("application.yaml"));
            prop.load(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"));
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
            this.conn = dataSource.getConnection();
            System.out.println("连接成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接失败");
        }
    }

    public ResultSet handleQuery(String query) {
        if (this.conn != null) {
            try {
                return this.conn.createStatement().executeQuery(query);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public void disconnect() {
        if (this.conn != null) {
            try {
                this.conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("关闭失败");
            }
        }
    }

}
